import configparser
import time
from datetime import datetime
from database_operations import databaseOperations
from webhook_sender_and_logger import webhookSenderAndLogger


class startOperations:
    def __init__(self):
        self._load_config()
        self.dbOperations = databaseOperations(self.server, self.user, self.password, self.database, self.charset,
                                               self.tdsVersion)
        self.webhookSender = webhookSenderAndLogger()

    def _load_config(self):
        config = configparser.ConfigParser()
        try:
            config.read('set.ini')
            self.server = config.get('Database', 'server')
            self.user = config.get('Database', 'user')
            self.password = config.get('Database', 'password')
            self.database = config.get('Database', 'database')
            self.charset = config.get('Database', 'charset')
            self.tdsVersion = config.get('Database', 'tds_version')
            self.selecttime = config.get('SelectTime', 'secs')
        except Exception as e:
            # 处理配置文件读取异常
            print(f"ini文件读取异常: {e}")
            # QMessageBox.waring(None,'警告','配置文件读取失败')

    def execute(self):
        while True:
            query_result = self.dbOperations.query(
                "select top 1 id,webhook_url,title,at,text,title_color,add_time from msg_detail where result is null  order by add_time ")
            getDate = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            if query_result:
                # 从查询结果中提取信息
                resultItem = query_result[0]
                resultId = resultItem[0]
                webhookUrl = resultItem[1]
                title = resultItem[2]
                at = resultItem[3]
                text = resultItem[4]
                titleColor = resultItem[5]

                # data_to_send = self.db_operations.get_data_for_webhook()
                resultWebhook = self.webhookSender.send_and_log(webhookUrl, title, at, text, titleColor)

                if resultWebhook == "success":
                    print(f"{getDate}:发送成功。")
                    self.dbOperations.updateQuery(
                        f"update msg_detail set result='{resultWebhook}' ,result_time='{getDate}' where id='{resultId}'")
                elif resultWebhook == "fail":
                    print(f"{getDate}:发送失败，请查看日志。")
                    self.dbOperations.updateQuery(
                        f"update msg_detail set result='{resultWebhook}' ,result_time='{getDate}' where id='{resultId}'")
                elif resultWebhook == "error":
                    print(f"{getDate}:发送失败，请求异常,调整后需重启服务。")
                    self.selecttime = 99999


            else:
                print(f"{getDate}:当前没有可用的消息推送，跳过此次执行。")

            time.sleep(int(self.selecttime))
